package com.zhl.gradledemo.controller;

import com.alibaba.fastjson.JSON;
import com.zhl.gradledemo.model.Article;
import com.zhl.gradledemo.model.BrokerMessageLog;
import com.zhl.gradledemo.model.Order;
import com.zhl.gradledemo.producer.OrderSender;
import com.zhl.gradledemo.service.ArticleService;
import com.zhl.gradledemo.service.BrokerMessageLogService;
import com.zhl.gradledemo.service.OrderService;
import com.zhl.gradledemo.util.HttpResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2020/02/11.
 * 发送消息(用于测试)
 */
@Controller
@Api(tags = "发送消息")
public class OederController {

    Logger logger = LoggerFactory.getLogger("ArticleController");


    @Resource
    private OrderSender orderSender;
    @Resource
    private OrderService orderService;
    @Resource
    private BrokerMessageLogService brokerMessageLogService;
    /**
     * 发送消息
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "发送消息", httpMethod = "GET")
    @GetMapping("/sendOrder")
    public HttpResult articleList() throws Exception {

        logger.info("===发送消息接口===");

        String uuid = UUID.randomUUID().toString().replace("-", "");
        //订单入库
        Order order = new Order();
        order.setId(uuid);
        order.setName("订单"+uuid);
        order.setMessageId(uuid);

        orderService.insert(order);

        //发送日志入库
        BrokerMessageLog brokerMessageLog = new BrokerMessageLog();
        Date date = new Date();

        brokerMessageLog.setMessageId(order.getMessageId());
        //将发送对象保存如日志,便于获取后再次发送
        brokerMessageLog.setMessage(JSON.toJSONString(order));
        //0 表示发送中
        brokerMessageLog.setTryCount(0);
        brokerMessageLog.setStatus("0");
        brokerMessageLog.setCreateTime(date);
        brokerMessageLog.setUpdateTime(date);
        //下次重试时间为1分钟后
        brokerMessageLog.setNextRetry(DateUtils.addMinutes(date, 1));
        brokerMessageLogService.insert(brokerMessageLog);

        orderSender.send(order);

        HttpResult zhlResult = HttpResult.suc(order);
        return zhlResult;

    }


    
}
